import axios from 'axios'
import Vue from 'vue'

import route from './router'

const http = axios.create({
    baseURL: 'http://localhost:3000/admin/api'
})

http.interceptors.request.use(config => {
    if(localStorage.token){
        config.headers.Authorization = 'Bearer ' + localStorage.token
    }
    return config
}, function(error) {
    return Promise.reject(error)
})

// 为全局添加一个拦截器
http.interceptors.response.use(res => {
    return res
}, err => {
    if(err.response.data.message){
        Vue.prototype.$message({
            type: 'error',
            message: err.response.data.message
        })

        if(err.response.status === 401){
            route.push('/login')
        }
    }
    return Promise.reject(err)
})

export default http